package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.FreemarkUtil;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyListObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext ctx;

    /*
    * 获取所有的区域
    * 资源:regions
    * 动作:GET
    * 参数:
    * */
    @GetMapping
    public Object list(Integer state){
        return regionService.query(state);
    }

    /*
     * 获取所有的区域
     * 资源:/regions/{strategyId}/strategies
     * 动作:GET
     * 参数:state=2&currentPage=x
     * */
    @GetMapping(value="/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void queryStrategies(StrategyListObject qo, HttpServletResponse resp) throws Exception{
        String dir = ctx.getRealPath("/template");
        Map<String,Object> map = new HashMap<>();
        map.put("id",qo.getRegionId());

        qo.setState(-1L);
        qo.setPageSize(2);
        PageInfo<Strategy> pageInfo = strategyService.query(qo);
        if(qo.getCurrentPage() != 1){
            map.put("info",pageInfo);
            FreemarkUtil.writeData(dir,"classify.ftl",map,resp.getWriter());
            return;
        }

        qo.setState(2L);
        qo.setPageSize(0);
        List<Strategy> commends = strategyService.query(qo).getList();
        map.put("commends",commends);
        map.put("info",pageInfo);
        FreemarkUtil.writeData(dir,"strategyContent.ftl",map,resp.getWriter());
    }
}
